import 'package:flutter/material.dart';
import 'package:x3_base_package/x3_base_package.dart';

class BusinessCustomerDetailsAddressEdit extends StatefulWidget {
  static String sName = 'BusinessCustomerDetailsAddressEdit';

  @override
  _BusinessCustomerDetailsAddressEditState createState() => _BusinessCustomerDetailsAddressEditState();
}

class _BusinessCustomerDetailsAddressEditState extends State<BusinessCustomerDetailsAddressEdit> {
  final List<BaseHttpRequestModel> _requestList = [
    BaseHttpRequestModel(fieldName: 'receiverName', name: '收件人', notes: '请填写收件人', required: true, inputType: BaseHttpInputTypeEnum.InputText, showType: BaseHttpShowTypeEnum.Text, accessMode: BaseHttpAccessModelEnum.WebReadWrite),
    BaseHttpRequestModel(fieldName: 'phoneNum', name: '手机号码', notes: '请输入手机号码', required: true, inputType: BaseHttpInputTypeEnum.InputText, showType: BaseHttpShowTypeEnum.Text, accessMode: BaseHttpAccessModelEnum.WebReadWrite, inputRegex: BaseUtils.getRegularPhoneNumber),
    BaseHttpRequestModel(fieldName: 'address', name: '所在地区', notes: '请选择省、市、区', required: true, inputType: BaseHttpInputTypeEnum.ChooseAddress, accessMode: BaseHttpAccessModelEnum.WebReadWrite),
    BaseHttpRequestModel(fieldName: 'detailAddress', name: '详细地址', notes: '请输入详细地址', required: true, inputType: BaseHttpInputTypeEnum.InputText, showType: BaseHttpShowTypeEnum.Text, accessMode: BaseHttpAccessModelEnum.WebReadWrite),
    BaseHttpRequestModel(fieldName: 'label', name: '标签', notes: '请选择标签', inputApi: '/vip/addressmanage/query/label', inputType: BaseHttpInputTypeEnum.SelectDialog, showType: BaseHttpShowTypeEnum.Text, accessMode: BaseHttpAccessModelEnum.WebReadWrite),
    BaseHttpRequestModel(fieldName: 'setDefault', name: '设置默认', notes: '请选择标签', defaultValue: '0', inputType: BaseHttpInputTypeEnum.Radio, showType: BaseHttpShowTypeEnum.Text, accessMode: BaseHttpAccessModelEnum.WebHidden),
  ];

  bool _isAdd = true;

  String _vipId;

  BaseRequestFormProvider baseRequestFormProvider;

  @override
  void initState() {
    baseRequestFormProvider = BaseRequestFormProvider(requests: _requestList);
    baseRequestFormProvider.dataSource.addAll({
      'label': {'key': 0, 'value': '未定义'}
    });
    super.initState();
  }

  @override
  void didChangeDependencies() {
    var argument = BaseRouterUtil.getArguments(context);
    _vipId = BaseUtils.getKeyData(argument, 'vipId');
    var _editDataSource = argument['dataSource'];
    if (_editDataSource != null) {
      _isAdd = false;
      _editDataSource['label'] = {'key': _editDataSource['label'], 'value': _editDataSource['labelName']};
      _editDataSource['address'] = {
        'province': _editDataSource['province'],
        'provinceId': _editDataSource['provinceId'],
        'city': _editDataSource['city'],
        'cityId': _editDataSource['cityId'],
        'area': _editDataSource['area'],
        'areaId': _editDataSource['areaId'],
      };
      baseRequestFormProvider.dataSource = _editDataSource;
    }
    super.didChangeDependencies();
  }

  @override
  Widget build(BuildContext context) {
    return BaseScaffoldComponent(
      title: _isAdd == true ? '新建收货地址' : '编辑收货地址',
      footerWidget: _footerWidget(),
      child: SingleChildScrollView(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            BaseCardComponent(child: BaseRequestForm(baseRequestFormProvider: baseRequestFormProvider)),
            _buildDefaultSetting(),
          ],
        ),
      ),
    );
  }

  Widget _footerWidget() {
    return BaseButton.bottom(text: '保存', onPress: _onSaveAddress);
  }

  Widget _buildDefaultSetting() {
    return BaseCardComponent(
      child: SwitchListTile(
        subtitle: Text('每次下单会默认推荐使用该地址', style: Theme.of(context).textTheme.subtitle2),
        contentPadding: EdgeInsets.all(0),
        title: Text('设置默认地址', style: Theme.of(context).textTheme.bodyText2.copyWith(fontSize: 14)),
        value: baseRequestFormProvider.dataSource['setDefault'] ?? false,
        onChanged: (value) {
          setState(() {
            baseRequestFormProvider.dataSource.addAll({'setDefault': value});
          });
        },
      ),
    );
  }

  void _onSaveAddress() async {
    baseRequestFormProvider.dataSource.addAll({'vipId': _vipId});
    bool isChecked = baseRequestFormProvider.validationDataSource();
    if (isChecked == true) {
      BaseHttpResultModel result;
      BaseComponentUtils.showLoadingDialog(context);
      Map<String, dynamic> params = {
        ...baseRequestFormProvider.dataSource,
        ...baseRequestFormProvider.dataSource['address'],
        'label': baseRequestFormProvider.dataSource['label']['key'],
        'labelName': baseRequestFormProvider.dataSource['label']['value'],
      };
      if (_isAdd) {
        result = await dioUtil.fetch('/vip/addressmanage/add', params: params);
      } else {
        result = await dioUtil.fetch('/vip/addressmanage/edit', params: params, method: BaseHttpMethodEnum.PUT);
      }
      BaseComponentUtils.hideLoadingDialog(context);
      if (result.success == true) Navigator.pop(context);
    }
  }
}
